package com.mygodp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mygodp.dto.Result;
import com.mygodp.dto.ScollResult;
import com.mygodp.dto.UserDTO;
import com.mygodp.entity.Blog;
import com.mygodp.entity.Follow;
import com.mygodp.entity.User;
import com.mygodp.mapper.BlogMapper;
import com.mygodp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mygodp.service.IUserService;
import com.mygodp.utils.RedisConstants;
import com.mygodp.utils.SystemConstants;
import com.mygodp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private FollowServiceImpl followService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            queryBlogUser(blog);
            isBlogLiked(blog);
        });

        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if(blog==null){
            return Result.fail("笔记不存在！");
        }
        queryBlogUser(blog);
        return Result.ok(blog);
    }
    private void isBlogLiked(Blog blog){
        // 1. 获取登录用户，先检查是否登录
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return;
        }
        //1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        String key= RedisConstants.BLOG_LIKED_KEY+ blog.getId();
        //2.判断当前登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);
    }
    @Override
    public Result likeBlog(Long id) {
        //1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        String key= RedisConstants.BLOG_LIKED_KEY+ id;
        //2.判断当前登录用户是否已经点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score==null){
            //3.如果未点赞，可以点赞
            //3.1.数据库点赞数+1
            boolean isSuccess = update().setSql("liked = liked +1").eq("id",id).update();
            if(isSuccess)
                // 3.2.保存用户到Redis的set集合
                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());

        }else {
            //4.如果已点赞，取消点赞
            // 4.1.数据库点赞数-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();

            //4.2.把用户从Redis的set集合移除
            if(isSuccess)
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
        }
        return Result.ok();
    }

    @Override
    public Result queryBlogLikes(Long id) {

        String key= RedisConstants.BLOG_LIKED_KEY+ id;
        //1.查询top5的点赞用户 zrange key 0 4
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        //2.解析出其中的用户id
        if(top5==null){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //3.根据id查用户 WHERE d IN(5,1)ORDER BY FIELD(id,5,1)
        String idStr = StrUtil.join(",", ids);
        List<User> users = userService.query()
                .in("id",ids).last("ORDER BY FIELD (id,"+ idStr+")").list();
        List<UserDTO> userDTOS = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2.保存探店笔记
        boolean isSuccess = save(blog);
        if(!isSuccess){
            return Result.fail("新增笔记失败！");
        }

        //3.查询笔记作者所有的粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        //4.推送笔记id给所有粉丝
        for (Follow f:follows) {
            //粉丝id
            String key= RedisConstants.FEED_KEY+f.getUserId();
            //推送
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1.获取登录用户
        Long userId = UserHolder.getUser().getId();
        //2.查询收件箱  ZREVRANGEBYSCORE KEY MAX MIN LIMIT offset count
        String key= RedisConstants.FEED_KEY+userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //3.非空判断
        if(typedTuples==null||typedTuples.size()==0){
            return Result.ok();
        }
        //4.解析数据 blogId,minTime(时间戳),offset
        int os =1;
        List<Long> ids = new ArrayList<>();
        long minTime=0;
       for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
           ids.add(Long.valueOf(typedTuple.getValue()));
           long time = typedTuple.getScore().longValue();
           if(time==minTime){
               os++;
           }else
               minTime=time;
               os=1;
       }
        String idStr = StrUtil.join(",", ids);
        //5.根据id批量查询
        List<Blog> blogs = query().in("id",ids).last(("ORDER BY FIELD (id,"+ idStr+")")).list();

        blogs.forEach(blog -> {
            queryBlogUser(blog);
            isBlogLiked(blog);
        });

        ScollResult r = new ScollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);
        return Result.ok(r);
    }

    private void queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


}